package cn.huaqingcheng.tianshu.infrastructure.start.repository;

import cn.huaqingcheng.tianshu.core.start.model.SiteGroup;
import cn.huaqingcheng.tianshu.core.start.repository.SiteGroupRepository;
import cn.huaqingcheng.tianshu.infrastructure.start.StartConvert;
import cn.huaqingcheng.tianshu.infrastructure.start.entity.SiteGroupEntity;
import cn.huaqingcheng.tianshu.infrastructure.start.mapper.SiteGroupMapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * SiteGroupRepositoryImpl
 */
@Repository
@RequiredArgsConstructor
public class SiteGroupRepositoryImpl implements SiteGroupRepository {

    private final SiteGroupMapper siteGroupMapper;


    @Override
    public List<SiteGroup> getAll(Long accountId) {
        List<SiteGroupEntity> list = new LambdaQueryChainWrapper<>(siteGroupMapper)
                .eq(SiteGroupEntity::getAccountId, accountId)
                .list();

        return list.stream()
                .map(StartConvert.INSTANCE::toModel)
                .toList();
    }

    @Override
    public Optional<SiteGroup> selectById(Long id) {
        return Optional.ofNullable(siteGroupMapper.selectById(id))
                .map(StartConvert.INSTANCE::toModel);
    }

    @Override
    public Map<Long, SiteGroup> selectMapByIds(List<Long> ids) {
        if (ids.isEmpty()) {
            return Map.of();
        }
        var list = siteGroupMapper.selectByIds(ids);

        return list.stream()
                .collect(Collectors.toMap(
                        SiteGroupEntity::getId,
                        StartConvert.INSTANCE::toModel
                ));
    }

    @Override
    public Long save(SiteGroup group) {
        SiteGroupEntity entity = StartConvert.INSTANCE.toEntity(group);
        siteGroupMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void update(SiteGroup group) {
        SiteGroupEntity entity = StartConvert.INSTANCE.toEntity(group);
        int i = siteGroupMapper.updateById(entity);
        if (i <= 0) {
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public void update(List<SiteGroup> group) {
        if (group.isEmpty()) {
            return;
        }
        List<SiteGroupEntity> entities = group.stream()
                .map(StartConvert.INSTANCE::toEntity)
                .toList();
        siteGroupMapper.updateById(entities);
    }

    @Override
    public void deleteById(Long id) {
        siteGroupMapper.deleteById(id);
    }

}
